package itsense.client;
import java.util.ArrayList;
import java.util.List;

import itsense.model.MemberDTO;

import com.smartgwt.client.widgets.events.ClickEvent;  
import com.smartgwt.client.widgets.events.ClickHandler; 

import com.smartgwt.client.widgets.events.CloseClickHandler;  
import com.smartgwt.client.widgets.events.CloseClientEvent;  
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DragDataAction;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.types.VerticalAlignment;

import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.validator.MatchesFieldValidator;
import com.smartgwt.client.widgets.form.validator.RegExpValidator;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.TransferImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.menu.MenuButton;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;


public class MemberListPanel extends Window {
	ListGrid memberGrid = new ListGrid();
	IButton addButton = new IButton("Add");
	public static MemberListPanel instance;
	
	public MemberListPanel() {
		instance = this;
		init();
	}
	
	private void init(){
		
		setTitle("Members");
		setWidth(900);
		setHeight(500);
		setCanDragResize(true);
		setCanDragReposition(true);
		
		memberGrid.setWidth100();  
		memberGrid.setHeight100();  
		memberGrid.setShowAllRecords(true);  
		memberGrid.setShowEmptyMessage(true);
		memberGrid.setEmptyMessage("<br>There are no members in the database");
		ListGridField idField = new ListGridField("id","Id");
		ListGridField passwordField = new ListGridField("password","Password");
		ListGridField memberLoginField = new ListGridField("login","Login");
		ListGridField emailField = new ListGridField("email","E-mail");
		ListGridField firstNameField = new ListGridField("firstName","First name");
		ListGridField lastNameField = new ListGridField("lastName","Last name");
		
		memberGrid.setFields(idField, memberLoginField,passwordField,emailField,firstNameField,lastNameField);
		
    	getMembersFromServer();
		
		addButton.setIcon("User-Administrator-Red-icon.png");  
		addButton.setIconOrientation("right");  
		addButton.setWidth(100);


	
		VLayout vLayout = new VLayout();
		vLayout.setWidth100();
		vLayout.setHeight100();
		vLayout.setMembersMargin(10);
		HStack hStack = new HStack();
		hStack.setMembersMargin(10);
		
		hStack.setHeight(30);
		hStack.addMember(addButton);
		
		vLayout.addMember(memberGrid);
		vLayout.addMember(hStack);
		addItem(vLayout);
		
		addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				BeautySenseGWT.memberListPanel.hide();
				BeautySenseGWT.memberListPanel.destroy();
				BeautySenseGWT.memberListPanel = null;
				BeautySenseGWT.memberMenuItem.setEnabled(true);
				
			}
		});

		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				new AddMemberWindow();
			}
		});
		
	}

	
	public void getMembersFromServer(){
	
	BeautySenseGWT.service.getMembers(new AsyncCallback<List<MemberDTO>>() {
		public void onSuccess(List<MemberDTO> result) {
			ListGridRecord[] memberList = new ListGridRecord[result.size()];
			for (int i = 0 ; i < result.size() ;i++){
				memberList[i] = new ListGridRecord();
				memberList[i].setAttribute("password", result.get(i).getPassword());
				memberList[i].setAttribute("id", result.get(i).getId());
				memberList[i].setAttribute("email", result.get(i).getEmail());
				memberList[i].setAttribute("firstName", result.get(i).getFirstName());
				memberList[i].setAttribute("lastName", result.get(i).getLastName());
				memberList[i].setAttribute("login", result.get(i).getLogin());
			}
			memberGrid.setData(memberList);
		}
		
		public void onFailure(Throwable caught) {
		}
	});
} 

}
//--------------------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------------------
class AddMemberWindow extends Window{
	public static AddMemberWindow instance;
	IButton cancelButton = new IButton("Cancel");
	IButton addButton = new IButton("Add");
	ListGrid leftListRoles = new ListGrid();
	ListGrid rightListRoles = new ListGrid();
	TabSet tabSetPanel = new TabSet();  
	Tab tabGeneral = new Tab("General", "User-Administrator-Blue-icon.png");
	Tab tabRoles = new Tab("General", "User-Administrator-Blue-icon.png");
	DynamicForm memberGeneralForm = new DynamicForm();  
	TextItem loginItem = new TextItem("login","Login");
	PasswordItem passwordItem = new PasswordItem("password","Password");
	PasswordItem password2Item = new PasswordItem("password2","Password again");
	TextItem emailItem = new TextItem("email","Email");  
	TextItem firstNameItem = new TextItem("firstName","First name");  
	TextItem lastNameItem = new TextItem("lastName","Last name");  
	TransferImgButton rightTransButton = new TransferImgButton(TransferImgButton.RIGHT);  
	TransferImgButton leftTransButton = new TransferImgButton(TransferImgButton.LEFT);  
	
	
	public AddMemberWindow() {
		instance = this;
		init();
	}
	
	
	private ListGridRecord[] getAvailabeRoles(){
		ListGridRecord[] roles = new ListGridRecord[3];
		roles[0] = new ListGridRecord();
		roles[0].setAttribute("role", "Admin");
		roles[1] = new ListGridRecord();
		roles[1].setAttribute("role", "Member");
		roles[2] = new ListGridRecord();
		roles[2].setAttribute("role", "Client");
		return roles;
	}

	private MemberDTO createMemberDTOFromFormFileds(){
		MemberDTO memberDTO = new MemberDTO();
		memberDTO.setEmail(memberGeneralForm.getValueAsString("email"));
		memberDTO.setFirstName(memberGeneralForm.getValueAsString("firstName"));
		memberDTO.setLastName(memberGeneralForm.getValueAsString("lastName"));
		memberDTO.setLogin(memberGeneralForm.getValueAsString("login"));
		memberDTO.setPassword(memberGeneralForm.getValueAsString("password"));
		ArrayList<Long> roles = new ArrayList<Long>();
		RecordList recList = rightListRoles.getDataAsRecordList();
		
		for (int i = 0 ; i < recList.getLength(); i++){
			String role = recList.get(i).getAttributeAsString("role");
			if ("Admin".compareTo(role) == 0) roles.add( new Long(0));
			if ("Member".compareTo(role) == 0) roles.add( new Long(1));
			if ("Client".compareTo(role) == 0) roles.add( new Long(2));
		}
		memberDTO.setRoles(roles);
		return memberDTO;
		
	}
		private void init(){
		setWidth(400);  
		setHeight(310);  
		setTitle("Edit member");  
		setShowMinimizeButton(false);
		setShowCloseButton(true);
		setIsModal(true);  
		setShowModalMask(true);  
		centerInPage();

		cancelButton.setWidth(100);
		cancelButton.setIcon("Cancel-2-icon.png");
		cancelButton.setIconOrientation("left");
		addButton.setIcon("accept-icon.png");  
		addButton.setIconOrientation("right");  
		addButton.setWidth(100);

		cancelButton.addClickHandler(new ClickHandler() {
			
			public void onClick(ClickEvent event) {
				AddMemberWindow.instance.hide();
				AddMemberWindow.instance.destroy();
				AddMemberWindow.instance = null;
			}
		});
		
		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if ( memberGeneralForm.validate() == true ){
					System.out.println("Validate form = true");
					
					MemberDTO memberDTO = createMemberDTOFromFormFileds();
					System.out.println("createMemberDTOFromFormFileds");

					BeautySenseGWT.service.addMember(memberDTO,new AsyncCallback<MemberDTO>() {
						
						public void onSuccess(MemberDTO result) {
							System.out.println("Add member");
							ListGridRecord rec = new ListGridRecord();
							rec.setAttribute("email", result.getEmail());
							rec.setAttribute("firstName", result.getFirstName());
							rec.setAttribute("lastName", result.getLastName());
							rec.setAttribute("login", result.getLogin());
							rec.setAttribute("id", result.getId());
							rec.setAttribute("password", result.getPassword());
							MemberListPanel.instance.memberGrid.addData(rec);
							
							AddMemberWindow.instance.hide();
							AddMemberWindow.instance.destroy();
							AddMemberWindow.instance = null;
						}
						
						public void onFailure(Throwable caught) {
							
						}
					} );
					
				}else{
				}
			}
		});
		
		
		tabSetPanel.setTabBarPosition(Side.TOP);  
		tabSetPanel.setTabBarAlign(Side.LEFT);
		tabSetPanel.setWidth100();  
		tabSetPanel.setHeight100();  
		
		// ------------------------------- DYNAMIC FORM
		memberGeneralForm.setHeight100();  
		memberGeneralForm.setWidth(280);  
		memberGeneralForm.setPadding(5);  
		memberGeneralForm.setLayoutAlign(VerticalAlignment.BOTTOM);  
		  
		loginItem.setRequired(true);
		passwordItem.setRequired(true);
		password2Item.setRequired(true);
		emailItem.setRequired(true);
		
		MatchesFieldValidator matchesValidator = new MatchesFieldValidator();
		matchesValidator.setOtherField("password");  
		matchesValidator.setErrorMessage("Passwords do not match");   
		password2Item.setValidators(matchesValidator);  
		
		RegExpValidator emailValidator = new RegExpValidator();  
		emailValidator.setErrorMessage("Invalid email address");  
		emailValidator.setExpression("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$");  
		emailItem.setValidators(emailValidator);  
		
		TextItem firstNameItem = new TextItem("firstName");  
		firstNameItem.setTitle("First name");
		
		TextItem lastNameItem = new TextItem("lastName");  
		lastNameItem.setTitle("Last name");
		memberGeneralForm.setFields(loginItem,passwordItem,password2Item,emailItem,firstNameItem,lastNameItem);  
	
		// ------------------------------- DYNAMIC FORM
		
		// ------------------------------- LISTS ON ROLES TAB
		leftListRoles.setWidth(120);
		leftListRoles.setFields(new ListGridField("role","Available roles"));
		leftListRoles.setCanDragRecordsOut(true);  
		leftListRoles.setCanAcceptDroppedRecords(true);  
		leftListRoles.setCanReorderFields(true);  
		leftListRoles.setDragDataAction(DragDataAction.MOVE);
		
		leftListRoles.setData(getAvailabeRoles());
		
		
		rightListRoles.setWidth(120);
		rightListRoles.setFields(new ListGridField("role","Current roles"));
		rightListRoles.setCanDragRecordsOut(true);  
		rightListRoles.setCanAcceptDroppedRecords(true);  
		rightListRoles.setCanReorderFields(true);  
		rightListRoles.setDragDataAction(DragDataAction.MOVE);
		// ------------------------------- LISTS ON ROLES TAB

		HStack hStack = new HStack();
		hStack.setHeight(30);
		hStack.setWidth100();
		hStack.addMember(cancelButton);
		hStack.addMember(addButton);
		hStack.setMembersMargin(10);
		hStack.setAlign(Alignment.CENTER);
		
		
		Tab generalTab = new Tab("General","User-Administrator-Blue-icon.png"); 
		Tab rolesTab = new Tab("Roles","User-Group-icon.png");
		
		tabSetPanel.addTab(generalTab);
		tabSetPanel.addTab(rolesTab);
		tabSetPanel.setWidth(350);
		tabSetPanel.setHeight(220);
		
		HStack hStack3 = new HStack();
		hStack3.setWidth100();
		hStack3.setHeight100();
		hStack3.setAlign(Alignment.CENTER);
		hStack3.addMember(memberGeneralForm);
		generalTab.setPane(hStack3);
		
		leftTransButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
					leftListRoles.transferSelectedData(rightListRoles);
			}
		});
		
		rightTransButton.addClickHandler(new ClickHandler() {
			
			public void onClick(ClickEvent event) {
				rightListRoles.transferSelectedData(leftListRoles);
				
			}
		});
		

		
		//-- ROLES TAB
		VStack vStack3 = new VStack();
		vStack3.setAlign(Alignment.CENTER);
		vStack3.setWidth(50);
		vStack3.setMembersMargin(20);
		vStack3.addMember(rightTransButton);
		vStack3.addMember(leftTransButton);
		
		HStack hStack2 = new HStack();
		hStack2.setMembersMargin(0);
		hStack2.setAlign(Alignment.CENTER);
		hStack2.addMember(leftListRoles);
		hStack2.addMember(vStack3);
		hStack2.addMember(rightListRoles);
	
		rolesTab.setPane(hStack2);

		// --- Zlozenie calego okna
		VStack vStack = new VStack();
		vStack.setMembersMargin(20);
		HStack hStack4 = new HStack();
		hStack4.setAlign(Alignment.CENTER);
		hStack4.addMember(tabSetPanel);

		vStack.addMember(hStack4);
		vStack.addMember(hStack);
		addItem(vStack);
		show();
	}	
	
};
//--------------------------------------------------------------------------------------------------------------------------
class EditMemberWindow extends Window{
	IButton cancelButton;
	IButton addButton;
	MemberListPanel owner;
	ListGrid leftList = new ListGrid();
	ListGrid rightList = new ListGrid();
	
	public EditMemberWindow(MemberListPanel owner) {
		this.owner = owner;
		init();
	}
	
	private void init(){
		
	}
}